package com.xt.base.wireless.server.udp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;

import org.apache.log4j.Logger;

/**
 * <br>
 * <br>
 * 
 * <p>
 * <a href="UDPServerListener.java.html"><i>查看源文件</i></a>
 * </p>
 * 
 * @author 杨洪波
 * @create-date:2010-9-12
 */
public class UDPServerListener implements Runnable {
	Logger log = Logger.getLogger(getClass());
	
	private DatagramSocket datagramSocket = null;
	private int port = 13828;
	private String receiveMsg;
	private long num = 0;
	/*private UDPServerThread udpServerThread = null;
	private List<UDPServerThread> threadLt = new ArrayList<UDPServerThread>();*/

	public UDPServerListener() {
		this.start();
	}

	public UDPServerListener(int port) {
		this.port = port;
		this.start();
	}
	
	public void start(){
		Thread th = new Thread(this);
		th.start();
	}

	public void run() {
		log.info("PC端MOA服务UDP监听器已启动...，端口："+port);
		try {
			DatagramSocket ds = new DatagramSocket(port);
			int size = 64*1024;
			byte[] bytes = null;
			DatagramPacket dp = null;
			SocketAddress address;
			
			while (true) {
				bytes = new byte[size];
				dp = new DatagramPacket(bytes,size);
				ds.receive(dp);
				address = dp.getSocketAddress();
				
				receiveMsg = new String(dp.getData(),0,dp.getData().length,"utf-8").trim();
				//udpServerThread = 
				if(num>=100000){
					log.info("UDP链接计数器已达到"+num+",需要归零，重新计数！");
					num = 0;
				}
				new UDPServerThread(address,receiveMsg,num+1);
				address = null;
				//threadLt.add(udpServerThread);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (datagramSocket != null)
					datagramSocket.close(); // 关闭ServerSocket
			} catch (Exception e) {
				log.info("关闭PC端MOA服务器端的socket时出错！", e);
			}
		}
		log.info("PC端MOA服务器端已关闭...");
	}

	public void setPort(int port) {
		this.port = port;
	}
}
